<template>
  <div>
    <el-card style="height: 100%">
      <div style="display: flex; height: 550px;">
        <el-card style="margin-right: 2%; height: 550px; width: 60%; overflow-y: auto">
          <div id="container" style="width: 100%; height: 510px;"></div>
        </el-card>
        <el-card style="flex: 0 0 50%;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1%">
            <div style="line-height: 3vh; background-color: #e1eaff; color: #5377d7; padding: 6px; border-radius: 4px; text-align: center">相关档案</div>
            <el-select v-model="category" placeholder="请选择" style="width: 30%; line-height: 3vh;" clearable>
              <el-option v-for="item in archivesCategory" :key="item.value" :label="item.label" :value="item">
              </el-option>
            </el-select>
          </div>
          <el-table v-loading="loading" :data="dataList" height="400" :show-header="false" style="overflow-y: auto"  @cell-dblclick="celldblclick">
            <el-table-column align="left">
              <template slot-scope="scope">
                <p class="ellipsis" style="height: 20px; font-weight: bold" :title="scope.row.XMMC || scope.row.TITLE">{{ scope.row.XMMC || scope.row.TITLE }}</p>
                <p><span style="font-weight: bold">摘要：</span>{{ scope.row.BZ }}</p>
                <p>
                  <span style="float: left; width: 50%">保管期限：{{ scope.row.BGQX }}</span>
                  <span style="float: right; width: 50%">时间：{{ scope.row.RQ }}</span>
                </p>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </div>
    </el-card>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen"
                     :celldbData="celldbData" @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose" :isDelete="1"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->
  </div>
</template>

<script>
import {fullText, getTyc} from "@/api/archive/retrieval/fullTextSearch";
import jianDetailsOpen from "@/components/componentsJianDetails";
import juanDetailsOpen from "@/components/componentsJuanDetails";
import { Graph, Model } from '@antv/x6'
import { ForceLayout } from '@antv/layout'

export default {
  name: "knowledgeGraph",
  props: ['knowTable', 'total', 'archivesCategory', 'tableHeaderList'],
  components: { jianDetailsOpen, juanDetailsOpen },
  data() {
    return {
      loading: true,
      dataList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      category: undefined,
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      height: '',
      width: '',
      keyword: undefined
    }
  },
  watch: {
    knowTable: {
      handler(valNew) {
        this.dataList = valNew
        this.loading = false
      },
      immediate: true,
      deep: true
    },
  },
  methods: {
    init(keyword) {
      this.keyword = keyword
      if (keyword != '' && keyword != undefined && keyword != null) {
        this.getSynonym(keyword)
      } else {
        document.getElementById("container").innerHTML = "";
      }
      this.loading = true
    },
    // 获取知识图谱
    getSynonym(keyword) {
      var arr = []
      if(keyword != "" && keyword != undefined){
        const words = keyword.split(/\s+/);
        for (let i = 0; i < words.length; i++) {
          arr.push(words[i])
        }
      }
      var form = {
        primary_word_array: arr,
      }
      getTyc(form).then(res => {
        document.getElementById("container").innerHTML = "";
        this.graph = new Graph({
          container: document.getElementById('container')
        });

        const layout = new ForceLayout({
          graph: this.graph,
        });
        const rawData = res;

        const data = {
          nodes: [],
          edges: [],
        };

        rawData.forEach((item) => {
          const primaryNode = { id: item.primary_word, label: item.primary_word, size: 50, x: 0, y: 0 };
          data.nodes.push(primaryNode);

          const tycNodes = item.tyc.split('，');
          tycNodes.forEach((tycNode) => {
            const targetNode = { id: tycNode, label: tycNode, size: 50, x: 0, y: 0 };
            data.nodes.push(targetNode);

            const edge = { source: item.primary_word, target: tycNode };
            data.edges.push(edge);
          });
        });

        const getModelFromOriginData = (data) => {
          const model = {
            nodes: [],
            edges: [],
          };
          data.nodes.forEach((item) => {
            model.nodes.push({
              id: item.id,
              shape: 'circle',
              width: item.size,
              height: item.size,
              label: item.label,
              x: item.x,
              y: item.y,
              attrs: {
                body: {
                  // fill: '#5F95FF',
                  fill: '#e1eaff',
                  stroke: 'transparent',
                  fontSize: 12, // 设置合适的字体大小
                },
              },
            });
          });
          data.edges.forEach((item) => {
            model.edges.push({
              source: item.source,
              target: item.target,
              attrs: {
                line: {
                  // stroke: '#A2B1C3',
                  stroke: '#5377d7',
                  strokeWidth: 2,
                  targetMarker: null,
                  fontSize: 12, // 设置合适的字体大小
                },
              },
            });
          });
          return model;
        };

        const forceLayout = new ForceLayout({
          type: 'force',
          center: [269, 180],
          preventOverlap: true,
          linkDistance: 100, // 设置所有边的长度为100
          nodeStrength: -50, // 节点之间斥力的参数
          edgeStrength: 0.1, // 弹簧力的强度
          tick: () => {
            const model = getModelFromOriginData(data)
            this.graph.fromJSON(model)
          },
        })
        forceLayout.layout(data)

        layout.execute();
        // var tycData = res.rows;
        //
        // // 计算每个tycData的位置
        // const calculatePositions = (tycData) => {
        //   const startX = 50; // 起始x坐标
        //   const startY = 50; // 起始y坐标
        //   const spacingX = 100; // 每个元素之间的x间距
        //   const spacingY = 50; // 每个元素之间的x间距
        //   const positions = [
        //     {x: 50, y: 50}
        //   ];
        //   for (let i = 0; i < tycData.length; i++) {
        //     const x = 100 + startX;
        //     const y = startY + i * spacingY;
        //     positions.push({ x, y });
        //   }
        //   return positions;
        // };
        //
        // const renderTycData = (tycData) => {
        //   document.getElementById("container").innerHTML = "";
        //   const container = document.getElementById("container");
        //   if (tycData.length==1) {
        //     this.height = '100%'
        //     this.width = '100%'
        //   } else {
        //     this.height = ''
        //     this.width = ''
        //   }
        //
        //   tycData.forEach((item, index) => {
        //     const tycArray = item.tyc.split("，");
        //     const positions = calculatePositions(tycArray);
        //     const svg = createSvgElement(positions, item.primary_word, tycArray);
        //     container.appendChild(svg);
        //   });
        // };
        //
        // const createSvgElement = (positions, primaryWord, tycArray) => {
        //   const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        //   svg.setAttribute("class", "svg-container");
        //   if (this.height == '' || this.width == '') {
        //     svg.style.height = positions[positions.length-1].y + 100;
        //   } else {
        //     svg.style.height = this.height
        //     svg.style.width = this.width
        //   }
        //
        //   const ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
        //   ellipse.setAttribute("class", "oval");
        //   ellipse.setAttribute("cx", "50");
        //   ellipse.setAttribute("cy", "50");
        //   ellipse.setAttribute("rx", "20");
        //   ellipse.setAttribute("ry", "10");
        //   ellipse.setAttributeNS(null, "fill", "lightblue");
        //   svg.appendChild(ellipse);
        //
        //   const foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
        //   foreignObject.setAttribute("x", "30");
        //   foreignObject.setAttribute("y", "70");
        //   foreignObject.setAttribute("width", "80"); // 设置foreignObject的宽度
        //   foreignObject.setAttribute("height", "100"); // 设置foreignObject的高度
        //
        //   const div = document.createElement("div");
        //   div.setAttribute("class", "text");
        //   div.style.fontSize = "12px";
        //
        //   div.innerText = primaryWord;
        //   foreignObject.appendChild(div);
        //   svg.appendChild(foreignObject);
        //
        //   tycArray.forEach((tyc, tycIndex) => {
        //     const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
        //     line.setAttribute("class", "arrow");
        //     line.setAttribute("x1", `${positions[0].x}`);
        //     line.setAttribute("y1", `${positions[0].y}`);
        //     line.setAttribute("x2", `${positions[tycIndex+1].x}`);
        //     line.setAttribute("y2", `${positions[tycIndex+1].y}`);
        //     line.setAttribute("marker-end", "url(#arrowhead)");
        //     line.setAttribute("stroke", "lightblue");
        //     line.setAttribute("stroke-width", "2");
        //     svg.appendChild(line);
        //
        //     const ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse");
        //     ellipse.setAttribute("class", "oval");
        //     ellipse.setAttribute("cx", `${positions[tycIndex+1].x}`);
        //     ellipse.setAttribute("cy", `${positions[tycIndex+1].y}`);
        //     ellipse.setAttribute("rx", "20");
        //     ellipse.setAttribute("ry", "10");
        //     ellipse.setAttributeNS(null, "fill", "lightblue");
        //     svg.appendChild(ellipse);
        //
        //
        //     const foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
        //     foreignObject.setAttribute("x", `${positions[tycIndex+1].x - 15}`);
        //     foreignObject.setAttribute("y", `${positions[tycIndex+1].y + 20}`);
        //     foreignObject.setAttribute("width", "80"); // 设置foreignObject的宽度
        //     foreignObject.setAttribute("height", "100"); // 设置foreignObject的高度
        //
        //     const div = document.createElement("div");
        //     div.setAttribute("class", "text");
        //     div.style.fontSize = "12px";
        //
        //     div.innerText = tyc;
        //     foreignObject.appendChild(div);
        //     svg.appendChild(foreignObject);
        //   });
        //
        //   return svg;
        // };
        //
        // renderTycData(tycData);
      });
    },
    getList() {
      this.$emit("getKnowList", this.queryParams)
    },
    celldblclick(row) {
      this.subStr = this.getLastIndexOf(row.sub_table_name);
      var level="";
      var type = "";
      var label = ""
      if (this.getLastIndexOf(row.sub_table_name) == "F") {  //F 件
        level = 0
        type = "f"
        label = row.TITLE
      } else if (this.getLastIndexOf(row.sub_table_name) == "V") { //卷
        level = 1
        type = "v"
        label = row.TITLE
      } else { //项目
        level = 3
        type = "x"
        label = row.XMMC
      }
      if (row.is_borrowing_car == '1') {
        var arr = []
        if(this.keyword != "" && this.keyword != undefined) {
          const words = this.keyword.split(/\s+/);
          for (let i = 0; i < words.length; i++) {
            arr.push(words[i])
          }
        }
        fullText({queryList: arr, daId: row.ID}).then(res=>{
          this.celldbData = {
            id: row.ID,
            categoryId: row.categoryId,
            menuId: this.$route.meta.menuId,
            sub_table_name: row.sub_table_name,
            label: label,
            level:level,
            ifSub_table_name:row.sub_table_name,
            isDel:"0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
            tableHeaderList: this.tableHeaderList,
            isBorrowingCar: row.is_borrowing_car,
            isElectronMatch: res // 电子件匹配信息
          }
          this.$nextTick(() => {
            if (this.subStr == "F") {  //F 进入件详情
              this.jianDetailsOpen = true;
            } else { //进入卷详情 和项目详情
              this.juanDetailsOpen = true
            }
          })
        })
      } else {
        this.celldbData = {
          id: row.ID,
          categoryId: row.categoryId,
          menuId: this.$route.meta.menuId,
          sub_table_name: row.sub_table_name,
          label: label,
          level:level,
          ifSub_table_name:row.sub_table_name,
          isDel:"0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList: this.tableHeaderList,
          isBorrowingCar: row.is_borrowing_car
        }
        this.$nextTick(() => {
          if (this.subStr == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      }
    },
    // 获取字符串中最后一个_前面的内容和获取最后一个"_"之后的内容
    getLastIndexOf(sub_table_name) {
      // 获取字符串中最后一个_前面的内容:
      var str = sub_table_name;
      var index = str.lastIndexOf("_");
      var strData = str.substring(0, index);
      //获取最后一个"_"之后的内容
      var index1 = strData.lastIndexOf("_");
      strData = strData.substring(index1 + 1, strData.length);
      return strData;
    },
    //关闭详情页面
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
  }
}
</script>

<style lang="scss" scoped>
.svg-container {
  width: 100%;
  height: 500px;
  position: relative;
}

.oval {
  fill: lightblue;
}

.arrow {
  stroke: lightblue;
  stroke-width: 2px;
  fill: none;
  marker-end: url(#arrowhead);
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
